# coding=utf8
from pymongo.collection import Collection

from zUtils.mongodb import mongodb_system_js, db
from zUtils.mongodb.ext import select_fields


class MongodbBase(Collection):
    def __init__(self, coll_name, indexs=None):
        super(MongodbBase, self).__init__(db, coll_name)
        if indexs:  # indexs是IndexModel的list
            self.create_indexes(indexs)

    def get_list_by_id(self, limit, sort=None, last_id=None, **kwargs):
        where = {}
        if last_id is not None:
            where.update({
                '_id': {'$gt': last_id}
            })
        if 'where' in kwargs:
            where.update(kwargs['where'])
        # sort格式 sort = [('_id',-1)]
        default_sort = [('_id', -1)]
        if sort and isinstance(sort, list):
            default_sort += sort
        return self.find(where).limit(limit).sort(default_sort)

    def get_list_by_page(self, start, limit, sort=None, exclude_fields=None, special_fields=None, **kwargs):
        where = {}
        if 'where' in kwargs:
            where.update(kwargs['where'])
        fields = {}
        if exclude_fields:
            fields.update(select_fields(exclude_fields, 0))
        if special_fields:
            fields.update(select_fields(special_fields, 1))

        default_sort = [('_id', -1)]
        if sort and isinstance(sort, list):
            default_sort += sort
        query = self.find(where, fields) if fields else self.find(where)
        return query.skip(start).limit(limit).sort(default_sort)

    @staticmethod
    def get_auto_increment_field(field_name):
        if not mongodb_system_js.list():
            try:
                import zUtils.mongodb.js
            except:
                pass
        return int(mongodb_system_js.getNextSequence(field_name))
